package com.github.xzb617.client.flow.core.rules;

import com.github.xzb617.client.flow.cache.CounterCache;
import com.github.xzb617.client.flow.core.FlowContext;
import com.github.xzb617.client.flow.core.FlowException;
import com.github.xzb617.client.flow.core.FlowLimiter;
import com.github.xzb617.client.flow.core.FlowProperties;
import com.github.xzb617.client.flow.core.rules.chain.Rule;
import com.github.xzb617.client.flow.core.rules.chain.RuleChain;
import com.github.xzb617.client.flow.core.rules.rule.IpRule;
import com.github.xzb617.client.flow.core.rules.rule.UrlRule;


import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class RulesFlowLimiter implements FlowLimiter {

    @Override
    public boolean enabled(FlowProperties flowConfig) {
        Boolean enabled = flowConfig.getRules().getEnabled();
        return Boolean.TRUE.equals(enabled);
    }

    @Override
    public void executeInternal(FlowContext flowContext, FlowProperties flowConfig, CounterCache counterCache, FlowLimiter limiterChain) throws FlowException {
        // 限流器链识别是否需要限流，需要限流就会抛出异常
        RuleChain ruleChain = this.buildRuleChain(flowConfig);
        ruleChain.validate(flowContext, flowConfig.getRules(), counterCache, ruleChain);
    }

    /**
     * 构建规则链
     * @param flowConfig 配置
     * @return
     */
    public RuleChain buildRuleChain(FlowProperties flowConfig) {
        return new RuleChain(buildRuleList(flowConfig));
    }

    private List<Rule> buildRuleList(FlowProperties flowConfig) {
        String supportRule = flowConfig.getRules().getSupportRule();
        List<Rule> rules = new ArrayList<>();
        if (supportRule.contains("IP")) {
            rules.add(new IpRule());
        }
        if (supportRule.contains("URL")) {
            rules.add(new UrlRule());
        }
        return rules;
    }
}
